package drukarnia.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;


import org.hibernate.Query;
import org.hibernate.Session;

import drukarnia.model.User;
import drukarnia.util.HibernateUtil;

public class UserManager extends HibernateUtil {
	
	public User register(User user){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		return user;
		
	}
	
	public boolean checkLoginIMail(String mail){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> lista = null;
		Query q = session.createQuery("from User where mail = '" + mail + "'");
		lista = q.list();
		
		boolean result = false;
		if(lista.isEmpty() == true)
			result = true;
		else
			result = false;
		session.getTransaction().commit();
		return result;
		
	}
	
	/**
	 * Metoda sluzaca do logowania Usera i sprawdzajaca czy podany User jest aktywowany oraz czy posiada prawa administratora
	 * @param login
	 * @param haslo
	 * @param request
	 * @return
	 */
	public boolean loguj(String mail, String haslo, HttpServletRequest request){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> lista = null;
		Query q = session.createQuery("from User where mail = '" + mail + "' and password = '" + haslo + "'");
		lista = q.list();
		
		boolean wynik = false;
		if(lista != null){
			for (User user : lista) {
				
				if(user.getAuthorization()=='a'){
					String admin = "TAK";
					request.setAttribute("admin", admin);
				}else if(user.getAuthorization() != 'a'){
					String admin = "NIE";
					request.setAttribute("admin", admin);
			
				}
				
				wynik = true;
			
			}	
		}else{
			wynik = false;
			
		}
		session.getTransaction().commit();
		return wynik;
		
	}
	
	/**
	 * Metoda sluzaca do wczytania podanego Usera z bazy na podstawie loginu
	 * @param login - login Usera ktorego chcesz zaladowac
	 * @return
	 */
	public User zaladujUsera(String mail){
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<User> lista = null;
		Query q = session.createQuery("from User where mail = '" + mail + "'");
		lista = q.list();
		User User = null;
		
		if(lista.isEmpty() == false){
			for (User user : lista) {
				User = (User) session.load(User.class, user.getId_user());
			}
		}
				
		session.getTransaction().commit();
		
		return User;
	}
	

}
